package org.ricks.conditon.test;

import org.ricks.conditon.Condition;
import org.ricks.ioc.event.IEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

public class ConditionManager {
    private final Map<Class<? extends IEvent>, List<Condition>> conditionMap = new ConcurrentHashMap<>();
    private final Logger logger = LoggerFactory.getLogger(getClass());

    public ConditionManager() {
        // 默认空构造，通过 register 方法添加条件
    }

    public <E extends IEvent> void register(Class<E> eventType, Condition condition) {
        conditionMap.computeIfAbsent(eventType, k -> new CopyOnWriteArrayList<>())
                .add(condition);
        logger.debug("Registered {} for {}", condition.getClass().getSimpleName(), eventType.getSimpleName());
    }

    public <E extends IEvent> void unregister(Class<E> eventType, Condition condition) {
        List<Condition> conditions = conditionMap.get(eventType);
        if (conditions != null && conditions.remove(condition)) {
            logger.debug("Unregistered {} from {}", condition.getClass().getSimpleName(), eventType.getSimpleName());
        }
    }

    public void handleEvent(IEvent event) {
        Class<? extends IEvent> eventType = event.getClass();
        List<Condition> conditions = conditionMap.getOrDefault(eventType, Collections.emptyList());
        conditions.forEach(condition -> {
            try {
                condition.emit(event);
            } catch (Exception e) {
                logger.error("Error processing {} by {}", eventType.getSimpleName(), condition.getClass().getSimpleName(), e);
            }
        });
    }
}
